package com;


import com.utils.SpringContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.unit.DataSize;

import javax.servlet.MultipartConfigElement;
import java.io.File;


/**
 * @author Yadasu
 * @date 2020/12/18 11:06
 */
@SpringBootApplication
@EnableScheduling
//指定entity所在的包并扫描带有@Entity注解的实体类
@EntityScan(basePackages = "com.entity")
//扫描Repository接口所在的包，生成动态代理实现类
@EnableJpaRepositories(basePackages = "com.repository")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

    }

    @Bean
    public SpringContextHolder springContextHolder() {
        return new SpringContextHolder();
    }
    //TODO:高耦合度，需降耦

    /**
     * 配置文件上传大小
     */
    @Bean
    public MultipartConfigElement getMultiConfig() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize(DataSize.parse("104857600"));
        factory.setMaxRequestSize(DataSize.parse("104857600"));
        String location = System.getProperty("user.home") + "/.testB/file/temp";
        File tmpFile = new File(location);
        if (!tmpFile.exists()) {
            if (!tmpFile.mkdirs()) {
                System.out.println("create was not successful.");
            }
        }
        factory.setLocation(location);
        return factory.createMultipartConfig();
    }

    /**
     * 密码编码器
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Bean("jdbcUseService")
    public JdbcDaoImpl userDetailService() {
        JdbcDaoImpl jdbcDao = new JdbcDaoImpl();
        jdbcDao.setJdbcTemplate(jdbcTemplate);
        jdbcDao.setUsersByUsernameQuery("select username,password,status  enable from sys_user where username=?");
        jdbcDao.setAuthoritiesByUsernameQuery("select username,r.name authority from \n" +
                "                sys_user u left join sys_user_role ur on u.id=ur.uid\n" +
                "                left join sys_role r on ur.rid=r.id\n" +
                "                where username=?");
        return jdbcDao;
    }
}


